package com.longlong.mvc;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * 负责接收所有请求
 *
 * @author longlong
 * @date 2025/1/25
 */
@Slf4j
public class DispatcherServlet extends HttpServlet {

    private final Handler handler = new Handler();

    @Override
    public void init(ServletConfig config) {
        //  加载配置文件
        handler.loadPropertiesFile();
        String packageNames = config.getInitParameter("scanPackage");
        if (packageNames != null) {
            // 扫描包
            handler.scanAnnotation(packageNames);
        }
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) {
        try {
            StringBuffer url = request.getRequestURL();
            log.info("===========================================================");
            log.info("收到一条请求 " + url.toString());
            //  href="AtmController.do?method=login&name=zzt&pass=123"
            //  获取请求路径  URI : /AtmController.do
            String uri = request.getRequestURI();
            log.info("请求路径是：" + uri);
            //  获取请求名  类名/方法名 AtmController/login
            String requestContent = handler.parseURI(uri);
            String methodName = request.getParameter("method");
            Object obj;
            if (methodName == null) {
                methodName = requestContent;
                log.info("请求方法名是：" + methodName);
                //  根据方法名 获取 类对象
                obj = handler.findObject(requestContent,"methodName");
            } else {
                log.info("请求类名是：" + requestContent);
                //  根据类名 获取 类对象
                obj = handler.findObject(requestContent,"className");
            }
            //  获取 方法对象
            Method method = handler.findMethod(obj, methodName);
            //  获取 参数值列表
            Object[] finalParamValue = handler.injectionParameters(method, request, response);
            //  执行方法
            Object result = method.invoke(obj, finalParamValue);
            log.info("方法执行完毕...");
            //  处理方法返回结果
            handler.finalResolver(obj, method, result, request, response);
            log.info("请求处理完成...");
            log.info("============================================================");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
